<?php

namespace app\api\model;

use app\admin\model\MemberModel;
use app\api\controller\Advise;
use app\api\validate\Source;
use think\Model;
use think\model\concern\SoftDelete;

class SourceModel extends ApiModel
{

    use SoftDelete;


    // 表名
    protected $name = 'source';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [

    ];

    public function member()
    {
        return $this->belongsTo(MemberModel::class, 'member_id', 'id', [], 'LEFT');
    }

    public function getAdvise($params)
    {
        $type = $params['type'] ?? 1;
        $map[] = ['status', '=', 1];
        if ($type == 1) {
            $map[] = ['member_id', '=', $params['uid']];
        } else {
            $map[] = ['member_id', '=', 0];
        }

        $list = self::where($map)->order('weigh desc,id desc')->field('id,company_name,phone')->paginate(10);

        if ($type == 2) {
            foreach ($list as &$value) {
                $value['phone'] = $this->maskPhoneNumber($value['phone']);
            }
        }
        return $this->api_success('获取成功', $list);
    }


    public function addAdvise($params)
    {
        $userAddressValidator = new Source();
        if (!$userAddressValidator->scene('add')->check($params)) {
            return $this->api_error($userAddressValidator->getError());
        }
        //添加
        $model = new self();
        $model->member_id = $params['uid'];
        $model->phone = $params['phone'];
        $model->company_name = $params['company_name'];
        if (!$model->save()) {
            return $this->api_error('添加失败');
        }
        return $this->api_success('添加成功');
    }


    public function updateAdvise($params)
    {
        $userAddressValidator = new Source();
        if (!$userAddressValidator->scene('add')->check($params)) {
            return $this->api_error($userAddressValidator->getError());
        }
        $advise = self::where(['id' => $params['id']])->find();
        if (!$advise) {
            return $this->api_error('数据不存在');
        }
        $advise->phone = $params['phone'];
        $advise->company_name = $params['company_name'];
        if (!$advise->save()) {
            return $this->api_error('修改失败');
        }
        return $this->api_success('修改成功');

    }


    public function deleteAdvise($params)
    {
        $advise = self::where(['id' => $params['id']])->find();
        if (!$advise) {
            return $this->api_error('数据不存在');
        }
        if (!$advise->delete()) {
            return $this->api_error('删除成功');
        }
        return $this->api_success('删除成功');

    }


    public function lookSource($params = array())
    {
        //获取用户信息
        $member = (new MemberModel())->where(['id' => $params['uid']])->find();
        //查询财税顾问等级
        $advise = (new HandlerModel())->where(['level' => $member['advise_level']])->find();
        if (!$advise) {
            return $this->api_error('您还没有开通财税顾问～');
        }
        $lookNums = $advise['nums'];

        $date = date('Y-m-d');
        $today = strtotime($date);
        $map[] = ['create_time', 'between', [$today, strtotime(date('Y-m-d 23:59:59', $today))]];
        //查询今天已经观看多少条
        $map[] = ['member_id', '=', $member['id']];
        $sources = (new SourceLog())->where($map)->count();
        if ($sources >= $lookNums) {
            //获取下一个等级
            $advise_last = (new HandlerModel())->where('level','>',$advise['level'])->order('level asc')->find();

            $isTopLevel  = false;
            if(!$advise_last){
                $isTopLevel  = true;
            }
            return $this->api_success('今天的次数已用完～',['advise'=>$advise_last,'isTopLevel'=>$isTopLevel]);
        }
        //查询客源信息
        $source = self::where(['id' => $params['source_id'], 'status' => 1])->field('id,company_name,phone')->find();
        if (!$source) {
            return $this->api_error('数据不存在，请刷新后重试～');
        }
        //添加记录
        $model = new SourceLog();
        $model->member_id = $member['id'];
        $model->source_id = $params['source_id'];
        $model->create_time = time();
        if (!$model->save()) {
            return $this->api_error('服务器错误');
        }
        return $this->api_success('获取成功', $source);
    }


    public function maskPhoneNumber($phoneNumber)
    {
        // 获取前三位数字
        $prefix = substr($phoneNumber, 0, 3);
        // 获取手机号长度
        $length = strlen($phoneNumber);

        // 将除了前三位以外的数字替换为 "*"
        $masked = $prefix . str_repeat('*', $length - 3);

        return $masked;
    }

}
